import axios from 'axios'
import { API_BASE_URL } from '../config/api'

// 创建 axios 实例
const request = axios.create({
    baseURL: API_BASE_URL,
    timeout: 10000
})

// 请求拦截器
request.interceptors.request.use(
    config => {
        const user = JSON.parse(localStorage.getItem('user'))
        if (user) {
            config.headers['X-Username'] = user.username
            config.headers['X-Role'] = user.role
        }
        return config
    },
    error => Promise.reject(error)
)

// 响应拦截器
request.interceptors.response.use(
    response => response,
    error => {
        if (error.response?.status === 401) {
            localStorage.removeItem('user')
            window.location.href = '/login'
        }
        return Promise.reject(error)
    }
)

export default request 